package com.snake.scoreboardlib;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import java.io.RandomAccessFile;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;

import android.content.Context;

import android.provider.Settings.Secure;


public class OSHelper {
	private static String duid;
	private static final String dateFormat = "dd-MM-yyyy HH:mm:ss.SSS";
	
	public static String DateToStr(Date date)
	{
		DateFormat df = new SimpleDateFormat(dateFormat);
		df.setTimeZone(TimeZone.getTimeZone("UTC"));

		return df.format(date);
	}
	public static Date StrToDate(String str) throws ParseException
	{
		DateFormat df = new SimpleDateFormat(dateFormat);
		df.setTimeZone(TimeZone.getTimeZone("UTC"));
		return df.parse(str);
		
	}
	public static Date StrToDateDef(String str, Date date)
	{
		DateFormat df = new SimpleDateFormat(dateFormat);
		df.setTimeZone(TimeZone.getTimeZone("UTC"));
		try {
			return df.parse(str);
		} catch (ParseException e) {
			return date;
		}
		
	}
	
	public synchronized static String GetDUID(Context context)
	{
		//if we already read duid, just return cached value
		if (duid != null)
			return duid;
		//read more about this http://android-developers.blogspot.com/2011/03/identifying-app-installations.html
		//trying to get ANDRIOD_ID
		duid = Secure.getString(context.getContentResolver(),
                Secure.ANDROID_ID);  
		
		if (duid == null)
		{
			// if we didn't get duid then we need to create it ourself and store it
			duid = Installation.DUID(context);
			
		}
		
		return duid ;
		 
	}
	
	
	public static class Installation {
	    private static final String INSTALLATION = "INSTALLATION";

	    public static String DUID(Context context) { 
	            File installation = new File(context.getFilesDir(), INSTALLATION);
	            try {
	                if (!installation.exists())
	                    writeInstallationFile(installation);
	                return readInstallationFile(installation);
	            } catch (Exception e) {
	                throw new RuntimeException(e);
	            }
	        
	    }

	    private static String readInstallationFile(File installation) throws IOException {
	        RandomAccessFile f = new RandomAccessFile(installation, "r");
	        byte[] bytes = new byte[(int) f.length()];
	        f.readFully(bytes);
	        f.close();
	        return new String(bytes);
	    }

	    private static void writeInstallationFile(File installation) throws IOException {
	        FileOutputStream out = new FileOutputStream(installation);
	        String id = UUID.randomUUID().toString();
	        out.write(id.getBytes());
	        out.close();
	    }	

	}

}
